package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.iuap.yms.param.SQLParameter;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.WarehouseMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.EventContent;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.LocationEntityService;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.WarehouseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ContentBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.WarehouseBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.PageBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WarehouseService {
    private static final Logger logger = LoggerFactory.getLogger(WarehouseService.class);

    @Autowired
    BaseService baseService;
    @Autowired
    private WarehouseMapperImpl warehouseMapper;
    @Autowired
    private LocationEntityService locationService;

    public WarehouseEntity SelectById(Long Id, String tenantId) {
        return warehouseMapper.selectById(Id, tenantId);
    }

    public Boolean CheckEntity(Long Id, String tenantId) {
        int rInt = warehouseMapper.selectCount(Id, tenantId);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(WarehouseEntity entity) {
        return warehouseMapper.insert(entity);
    }

    public Integer UpdateEntity(WarehouseEntity entity) {
        return warehouseMapper.updateByPrimaryKey(entity);
    }

    public List<WarehouseEntity> SelectAll(String tenantId) {
        return warehouseMapper.selectAll(tenantId);
    }

    public Integer DeleteById(Long Id, String tenantId) {
        return warehouseMapper.deleteByPrimaryKey(Id, tenantId);
    }

    //新增并更新
    public Integer InsertBatch(List<WarehouseEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = warehouseMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    public void AutoDataEdit(EventContent content) throws IOException {
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        WarehouseEntity warehouseEntity = EventEdit(content);
        //同步到货位表
        String yhtUserId = obj.getYhtUser();
        String tenantId = content.getTenantId();
        if (warehouseEntity != null && warehouseEntity.getId() > 0) {
            W2LocationById(tenantId, String.valueOf(warehouseEntity.getId()));
        }
    }

    public static LocationEntity W2LocationEntity(WarehouseEntity warehouseEntity, String tenantId, String yhtUserId) {
        //仓库信息更新到货位表
        LocationEntity entity = new LocationEntity();
        entity.setId(warehouseEntity.getId().toString());
        entity.setLevel(0);
        entity.setSort_num(0);
        entity.setIsEnd(false);
        entity.setPath(String.format("%s|", warehouseEntity.getId().toString()));
        entity.setTenant_id(tenantId);
        entity.setName(warehouseEntity.getWarehouseName());
        entity.setLocationName(warehouseEntity.getWarehouseName());
        entity.setLocationCode(warehouseEntity.getCode());
        entity.setWarehouse_id(warehouseEntity.getId().toString());
        entity.setWarehouse_code(warehouseEntity.getCode());
        entity.setWarehouse_name(warehouseEntity.getWarehouseName());
        entity.setDr(0);
        entity.setOrg_id(warehouseEntity.getOrg());
        entity.setModifier(yhtUserId);
        entity.setModify_time(warehouseEntity.getModifyTime());
        entity.setCreator(yhtUserId);
        entity.setCreate_time(warehouseEntity.getCreateTime());
        return entity;
    }

    /**
     * 订阅直接更新仓库信息
     * @param content
     * @return
     * @throws IOException
     */
    public WarehouseEntity EventEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        String jsonString = obj.getArchive().replace("detail!id", "detailid").replace("detail!", "");
        WarehouseBean warehouseBean = RequestTool.getBean(jsonString, WarehouseBean.class);
        String itemName = "";
        if (warehouseBean.getName() != null) {
            itemName = warehouseBean.getName().getZh_CN();
        }
        WarehouseEntity warehouseEntity = RequestTool.getBean(jsonString, WarehouseEntity.class);
        warehouseEntity.setWarehouseName(itemName);
        warehouseEntity.setTenantId(obj.getTenantId());
        if (warehouseEntity.getiUsed() != null && warehouseEntity.getiUsed().equals("enable"))
            warehouseEntity.setIsEnabled("true");
        if (warehouseEntity.getIsEnabled() != null && warehouseEntity.getIsEnabled().equals("true"))
            warehouseEntity.setiUsed("enable");
        String yhtUserId = obj.getYhtUser();
        if (StringUtils.isEmpty(warehouseEntity.getCreator())) {
            warehouseEntity.setCreatorId(yhtUserId);
            warehouseEntity.setCreator(yhtUserId);
        }
        warehouseEntity.setModifier(yhtUserId);
        warehouseEntity.setModifierId(yhtUserId);

//        System.out.println(JSON.toJSONString(warehouseEntity));
        Boolean flag = CheckEntity(warehouseEntity.getId(), warehouseEntity.getTenantId());
        if (flag) {
            int rInt = UpdateEntity(warehouseEntity);
            if (rInt > 0) return warehouseEntity;
        } else {
            int rInt = InsertEntity(warehouseEntity);
            if (rInt > 0) return warehouseEntity;
        }
        return warehouseEntity;
    }

    public Integer EventDel(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        Long Id = Long.parseLong(obj.getId());
        Boolean flag = CheckEntity(Id, obj.getTenantId());
        if (flag) {
            int rInt = DeleteById(Id, obj.getTenantId());
            return rInt;
        }
        return 0;
    }

    /**
     * 自动更新货位表同步变更数据
     * 触发条件：仓库名称发生变化
     *
     * @param Key           修改前名称
     * @param WarehouseName 修改后名称
     * @param WarehouseCode 修改后编码
     */
    public void AutoEditLocationEntity(String Key, String WarehouseName, String WarehouseCode, String tenantId) {
        try {
            Map<String, Object> params = new HashMap();
            params.put("key", Key);
            params.put("tenant", tenantId);
            params.put("warehousename", WarehouseName);
            params.put("warehousecode", WarehouseCode);
            Map<String, Object> params2 = new HashMap();
            params2.put("key", Key);
            params2.put("tenant", tenantId);
            params2.put("warehousename", WarehouseName);
        } catch (Exception ex) {
            logger.error("[AutoEditLocationEntity]" + ex.getMessage());
        }
    }

    public void AutoDelLocationEntity(Long Key, String tenantId) {
        try {
            locationService.DeleteByPrimaryKey(String.valueOf(Key), tenantId);
        } catch (Exception ex) {
            logger.error("[AutoDelLocationEntity]" + ex.getMessage());
        }
    }


    public List<WarehouseEntity> SelectByOrgIds(List<String> orgIds, String tenantId) {
        return warehouseMapper.GetwarehouseByorgIds(orgIds, tenantId);
    }

    // 同步仓库列表
    public int EventProductEdit(String tenantId, String key, String val, String userId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        int recordCount = 0;
        int errerCount = 0;
        int curPageIndex = 0;
        boolean flagNext = true;
        try {
            while (flagNext) {
                AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
                String token = MyToken.getAccessToken();
                String requrl = gatewayUrl + ApiYon.getWarehoseList + "?access_token=" + token;
                Map<String, Object> params = new HashMap<>();
                // 除签名外的其他参数
                params.put("pageIndex", String.valueOf(curPageIndex + 1));
                params.put("pageSize", "10");
                if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(val)) {
                    params.put("simple", JSONObject.parse("{\"" + key + "\":\"" + val + "\"}"));
                } else if (!StringUtils.isEmpty(val)) {
                    params.put("code", val);
                }
                String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
                /** 数据与在线工具调试显示数据不一致 数据少
                 * {"code":"200","message":"操作成功","data":{"pageIndex":1,"pageSize":10,"recordCount":1,
                 * "recordList":[{"code":"000001","bMRP":true,"ownerorg_name":"河北运营中心","isInvertedScour":false,"isBatchNumberManage":1,
                 * "isGoodsPosition":false,"id":1664464737247690753,"pubts":"2023-02-21 16:46:38","org_name":"河北运营中心","eStore":false,
                 * "isWasteWarehouse":false,"creator":"魏宪民","org":"1661277115591426054","ownerorg":"1661277115591426054","wStore":false,
                 * "stockCheckType":0,"isCarSales":false,"createTime":"2023-02-21 16:46:38","bWMS":false,"iUsed":"enable","countCost":false,
                 * "name":"德鑫泉-河北仓","iSerialManage":true,"org_code":"hb001"}],"pageCount":1,"beginPageIndex":1,"endPageIndex":1}}
                 */
                GenericResponse<PageBean<WarehouseBean>> response = RequestTool.getBean(resString,
                        new TypeReference<GenericResponse<PageBean<WarehouseBean>>>() {
                        });

                List<WarehouseEntity> myData = new ArrayList<>();
                if (response.getCode().equals("200")) {
                    curPageIndex = response.getData().getPageIndex();
                    int endPageIndex = response.getData().getEndPageIndex();

                    List<WarehouseBean> resDataWarehouse = response.getData().getRecordList();
                    if (resDataWarehouse == null || resDataWarehouse.size() == 0) {
                        flagNext = false;
                        break;
                    }
                    for (WarehouseBean item : resDataWarehouse) {
                        WarehouseEntity obj = MyTool.convertBean2Bean(item, WarehouseEntity.class);
                        obj.setTenantId(tenantId);
                        obj.setWarehouseName(item.getName() != null ? item.getName().getZh_CN() : null);
                        if (item.getiUsed() != null && item.getiUsed().equals("enable")) obj.setIsEnabled("true");
                        if (item.getIsEnabled() != null && item.getIsEnabled().equals("true")) obj.setiUsed("enable");
                        if (StringUtils.isEmpty(obj.getCreator())) {
                            obj.setCreatorId(userId);
                            obj.setCreator(userId);
                        }
                        obj.setModifier(userId);
                        obj.setModifierId(userId);
                        myData.add(obj);
                    }
                    int rIntNew = InsertBatch(myData);
                    Integer rInt = WarehouseToLocation(myData, tenantId, userId);
                    recordCount += rInt;
                    // 同步到货位表
                    System.out.println("EventProductEdit影响条数" + rIntNew);
                    if (endPageIndex <= curPageIndex) flagNext = false;
                } else {
                    errerCount++;
                }
                if (errerCount >= 3) flagNext = false;
            }
        } catch (Exception ex) {
            logger.error("[EventProductEdit]" + ex.getMessage());
        }
        return recordCount;
    }

    /**
     * 同步仓库列表 仅更新本地货位表仓库信息
     * @param tenantId
     * @param warehouseId
     * @param userId
     * @return
     * @throws IOException
     */
    public int EventProductEditById(String tenantId, String warehouseId, String userId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        int recordCount = 0;
        try {
            AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
            String token = MyToken.getAccessToken();
            String requrl = gatewayUrl + ApiYon.getWarehoseDetail + "?access_token=" + token;
            Map<String, String> params = new HashMap<>();
            // 除签名外的其他参数
            params.put("id", warehouseId);
            String resString = RequestTool.doGet(requrl, params);
            GenericResponse<WarehouseBean> response = RequestTool.getBean(resString,
                    new TypeReference<GenericResponse<WarehouseBean>>() {
                    });
            if (!response.getCode().equals("200")) {
                throw new RuntimeException(resString);
            }
            List<WarehouseEntity> myData = new ArrayList<>();
            if (response.getCode().equals("200")) {
                WarehouseBean item = response.getData();
                if (item == null) return 0;
                WarehouseEntity obj = MyTool.convertBean2Bean(item, WarehouseEntity.class);
                obj.setTenantId(tenantId);
                obj.setWarehouseName(item.getName() != null ? item.getName().getZh_CN() : null);
                if (item.getiUsed() != null && item.getiUsed().equals("enable")) obj.setIsEnabled("true");
                if (item.getIsEnabled() != null && item.getIsEnabled().equals("true")) obj.setiUsed("enable");
                if (StringUtils.isEmpty(obj.getCreator())) {
                    obj.setCreatorId(userId);
                    obj.setCreator(userId);
                }
                obj.setModifier(userId);
                obj.setModifierId(userId);
                myData.add(obj);
                int rIntNew = InsertBatch(myData);
                Integer rInt = WarehouseToLocation(myData, tenantId, userId);
                recordCount += rInt;
                System.out.println("EventProductEditById影响条数" + rIntNew);
            }
        } catch (Exception ex) {
            logger.error("[EventProductEditById]" + ex.getMessage());
        }
        return recordCount;
    }

    /**
     * 同步到货位表 仅更新仓库信息
     * 增加是否需要同步标识 warehouse_name 为空时 需要更新
     *
     * @param myData
     * @param tenantId
     * @param yhtUserId
     * @return
     */
    private Integer WarehouseToLocation(List<WarehouseEntity> myData, String tenantId, String yhtUserId) {
        int countRes = 0;
        List<LocationEntity> listEntity = new ArrayList<>();
        List<String> wids = myData.stream().map(it -> it.getId().toString()).collect(Collectors.toList());
        List<LocationEntity> tempWEntity = locationService.getLocationByIds(wids, tenantId);
        for (WarehouseEntity item : myData) {
            LocationEntity entity = W2LocationEntity(item, tenantId, yhtUserId);
            LocationEntity tempEntity = tempWEntity.stream().filter(it -> it.getId().equals(String.valueOf(item.getId()))).findAny().orElse(null);
            if (tempEntity != null && !tempEntity.getWarehouse_name().equals(item.getWarehouseName())) {
                entity.setWarehouse_name("");//warehouse_name 为空时 需要更新
            }
            listEntity.add(entity);
        }
        Integer rInt = locationService.InsertBatch(listEntity);
        countRes += rInt;
        return countRes;
    }

    /**
     * 同步到货位表 并更新关联货位数据信息
     * @param tenantId
     * @param warehouseId
     * @return
     */
    public boolean W2LocationById(String tenantId, String warehouseId) {
        WarehouseEntity warehouseEntity = SelectById(Long.parseLong(warehouseId), tenantId);
        if (warehouseEntity == null) {
            return false;
        }
        //同步到货位表
        String yhtUserId = warehouseEntity.getModifierId();
        LocationEntity model = null; //不存在时写入，存在更新
        List<LocationEntity> listLocationEntity = new ArrayList<>();
        if (warehouseEntity != null && warehouseEntity.getId() > 0) {
            List<LocationEntity> listEntity = locationService.GetLocationByWarehouseId(warehouseEntity.getId().toString()
                    , tenantId);
            if (listEntity == null || listEntity.size() == 0) {
                LocationEntity entity = W2LocationEntity(warehouseEntity, tenantId, yhtUserId);
                listLocationEntity.add(entity);
                int rInt = locationService.InsertBatch(listLocationEntity);
                return true;
            }
            model = listEntity.stream().filter(it -> it.getLevel() == 0).collect(Collectors.toList()).get(0);
            //仓库信息修改触发
            //更新仓库名称、更新仓库子集parentName
            if (model != null && !model.getWarehouse_name().equals(warehouseEntity.getWarehouseName())) {
                String WarehouseName = warehouseEntity.getWarehouseName();
                //更新仓库名称
                model.setWarehouse_name(WarehouseName);
                listLocationEntity.add(model);
                listEntity.stream().filter(it -> it.getParent_id() == warehouseId).forEach(item -> {
                    item.setParent_name(WarehouseName);
                    listLocationEntity.add(item);
                });
                int rInt = locationService.InsertBatch(listLocationEntity);
            }
        }
        return true;
    }
    public Integer ExeSQL(String sql, SQLParameter parameter){
        return warehouseMapper.ExeSQL(sql, parameter);
    }
}
